#include "list.h"

void list_init(struct list* list)
{
	list->head.pre = NULL;
	list->head.next = &list->tail;
	
	list->tail.pre = &list->head;
	list->tail.next = NULL;
}

// add head
void list_insert(struct list* list, struct list_item* item)
{
	item->next = list->head.next;
	list->head.next = item;
	
	item->next->pre = item;
	item->pre = &list->head;
}

void list_remove(struct list_item* item)
{
	struct list_item* pre = item->pre;
	struct list_item* next = item->next;
	
	pre->next = next;
	next->pre = pre;
}

void list_append(struct list* list, struct list_item* item)
{
	item->pre = list->tail.pre;
	list->tail.pre = item;
	
	item->pre->next = item;
	item->next = &list->tail;
}

void list_push(struct list* list, struct list_item* item)
{
	list_insert(list, item);
}

struct list_item* list_pop(struct list* list)
{
	struct list_item* first = list->head.next;
	if (first == &list->tail)
		return NULL;
	
	list_remove(first);
	
	return first;
}

int8_t list_empty(struct list* list)
{
	return list->head.next == &list->tail;
}

uint32_t list_size(struct list* list)
{
	uint32_t size = 0;
	
	struct list_item* item = list->head.next;
	while (item != &list->tail)
	{
		++size;
		item = item->next;
	}
	
	return size;
}
